var express = require('express')
var router = express.Router()
const sqlQuery = require('../../../module/sqlQuery')
const { resJsonObject } = require('../../../module/canshu')

/**
 * 返回所有分类类别数据
 */
async function getCategoryList() {
  const results = await sqlQuery('select * from doctors_category')
  return results
}

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.render('admin/doctors/doctors/doctorsList')
})

router.get('/data', async function (req, res, next) {
  try {
    // keywords 搜索关键词 为空的时候 查询全部
    let { page, limit, keywords_name = '' } = req.query
    console.log(req.query)

    page = parseInt(page ? page : 1)
    limit = parseInt(limit)
    const results = await sqlQuery(
      `SELECT 
      doctorslist.id as id,
      doctorslist.name as doctorslist_name,
      category_id,
      doctors_category.name as category_name
      FROM doctorslist 
      LEFT JOIN doctors_category 
      ON doctorslist.category_id=doctors_category.id 
      where status=1 and doctorslist.name like ? limit ?,?`,
      ['%' + keywords_name + '%', (page - 1) * 5, limit]
    )

    // 符合条件的总条数
    const [
      { count_num },
    ] = await sqlQuery(
      'select count(*) as count_num from doctorslist where status=1 and name like ?',
      ['%' + keywords_name + '%']
    )

    res.json(
      resJsonObject({
        code: 0,
        msg: '完成',
        data: {
          arr: Array.from(results),
          count: count_num,
        },
      })
    )
    // res.render('admin/users/userlist',{userlist:results});
  } catch (error) {
    console.log(error)
    res.json(
      resJsonObject({
        code: 1,
        msg: '获取失败',
        data: {
          error,
        },
      })
    )
  }
})

// 信息界面 添加
router.get('/add', async function (req, res, next) {
  // 获取分类列表
  const categoryList = await getCategoryList()
  const options = { categoryList, doctorinfo: { categoryid: 1 } }

  res.render('admin/doctors/doctors/addDoctor', options)
})

router.post('/add', async function (req, res, next) {
  try {
    console.log(req.body)
    const { name, category_id } = req.body

    const sqlStr = `insert into doctorslist (name,category_id,status) values (?,?,?)`
    await sqlQuery(sqlStr, [name, parseInt(category_id), 1])
    // console.log(results)
    res.json(
      resJsonObject({
        code: 0,
        msg: '添加成功',
      })
    )
  } catch (error) {
    console.log(error)
    res.json(
      resJsonObject({
        code: 1,
        msg: '添加失败',
        data: {
          error,
        },
      })
    )
  }
})

// 用户信息删除（update状态改位为 0 ）
router.post('/delete', async function (req, res, next) {
  // console.log(req.body)
  const { id } = req.body

  console.log(id);

  // 用户信息删除（update状态改位为 0 ）
  // const { username, password, email, mobile, roleid } = req.body
  const results = await sqlQuery(
    'update doctorslist set status = 0 where id=?',
    [id]
  )
  res.json(
    resJsonObject({
      code: 0,
      msg: '删除成功',
      data: {
        results,
      },
    })
  )
})

// 信息界面 编辑
router.get('/edit/:id', async function (req, res, next) {
  let sqlStr = `select * from doctorslist where id=?`

  // 获取分类列表
  const categoryList = await getCategoryList()

  // 获取角色列表
  const results = await sqlQuery(sqlStr, [req.params.id])
  // res.json(results)
  const options = { doctorinfo: results[0], categoryList }
  res.render('admin/doctors/doctors/editDoctor.ejs', options)
})

router.post('/edit', async function (req, res, next) {
  try {
    let { doctorid, name, category_id } = req.body

    // authlist = JSON.parse(authlist)

    // 1，更新角色表，
    const resultForRoleListTable = await sqlQuery(
      'update doctorslist set name =?,category_id =? where id=?',
      [name, category_id, parseInt(doctorid)]
    )

    // 2，更新角色权限关联表

    // // 先删除原有的该角色的权限信息
    // await sqlQuery('delete from role_auth where roleid=?', [roleid])

    // // 添加新的角色权限信息
    // authlist.forEach(async (item) => {
    //   await sqlQuery(`insert into role_auth (roleid,authid)
    //   values (${parseInt(roleid)},${parseInt(item.value)}); `)
    // })

    res.json(
      resJsonObject({
        code: 0,
        msg: '更新成功',
      })
    )
  } catch (error) {
    console.log(error)
    res.json(
      resJsonObject({
        code: 1,
        msg: '更新失败',
        data: {
          error,
        },
      })
    )
  }
})



module.exports = router
